home *** CD-ROM | disk | FTP | other *** search
/ Cream of the Crop 22 / Cream of the Crop 22.iso / os2 / edm0407s.zip / SEMSRC.ZIP / EXAMPLE.CPP next >
C/C++ Source or Header  |  1996-06-26  |  2KB  |  100 lines

  1. /*
  2.     This has been compiled under Watcom C++ 10.5
  3.     It should compile with little or no modifications with other
  4.     compilers, but it has not been tested.
  5.  
  6.     wcl386 -bm example.cpp
  7. */
  8.  
  9. #include <process.h> // for _beginthread
  10.  
  11. #include <iostream.h>
  12. #include <string.h>
  13.  
  14. #include <string.hpp>
  15. typedef String string; // fake the upcoming standard string library
  16.  
  17. #include "sync.h"
  18.  
  19. const STACKSIZE=1024*8;
  20.  
  21. struct Blob
  22. {
  23.     Blob(Event* e, Mutex* m): event(e), mutex(m) {}
  24.     void Calc()
  25.     {
  26.     char* str="Important message";
  27.     for (int i=0; i< strlen(str); i++)
  28.         cout<<str[i];
  29.     cout<<endl;
  30.     }
  31.     
  32.     Event* event;
  33.     Mutex* mutex;
  34. };
  35.  
  36. void workerThread(void* arg);
  37.  
  38. /*
  39.     This program demonstrates the necessity of syncronising
  40.     threads.  The shared resource in this example is the screen.
  41.     Without syncronisation, the output of the multiple threads
  42.     is intermixed, creating unreadable output.
  43.  
  44.     To see the program use syncronisation, run the program without
  45.     any arguments.  To see the chaos that results without any
  46.     syncronisation, run the program with one argument.
  47. */
  48. int main(int argc, char* [])
  49. {
  50.     Event done;
  51.     Mutex m,*pm;
  52.     ULONG nDone=0,tmpDone=0;
  53.     const MAXTASKS=10;
  54.  
  55.     if (argc!=1)
  56.     pm=NULL;
  57.     else
  58.         pm=&m;
  59.  
  60.     Blob blob(&done,pm);
  61.     
  62.     for (int i=0; i<MAXTASKS; i++)
  63.     {
  64.         _beginthread(workerThread, NULL, STACKSIZE, &blob);
  65.     // use _beginthread to start a thread if it is going to utilise
  66.     // any c or C++ library routines.  Other compilers may have
  67.     // slightly different function parameters.
  68.     }
  69.     
  70.     while (nDone!=MAXTASKS)
  71.     {
  72.         done.Wait();
  73.     tmpDone=0;
  74.     done.Reset(&tmpDone);
  75.     nDone=nDone+tmpDone;
  76.     // This loop uses an event semaphore to wait until
  77.     // all the threads are done.
  78.     }
  79.     return 1;
  80. }
  81.  
  82. void workerThread(void* arg)
  83. {
  84.     Blob* pb=(Blob*)arg;
  85.  
  86.     if (pb->mutex)
  87.     {
  88.         MutexLock lock(pb->mutex);
  89.            for (int i=0; i<2; i++)
  90.             pb->Calc();
  91.     }
  92.     else
  93.     {
  94.     for (int i=0; i<2; i++)
  95.         pb->Calc();
  96.     }
  97.     pb->event->Post();
  98. }
  99.  
  100.